package com.sie.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.hustcad.plm.basic.entity.TyplmObjectAliasDO;
import com.hustcad.plm.basic.log.LogEventEnum;
import com.hustcad.plm.basic.service.TyplmObjectAliasService;
import com.hustcad.plm.basic.service.impl.BaseEntityServiceImpl;
import com.hustcad.plm.basic.util.TyplmEntityBaseUtil;
import com.hustcad.plm.basic.util.TyplmLoggerUtil;
import com.hustcad.plm.basic.util.TyplmPinYinUtil;
import com.hustcad.plm.pdm.access.service.TyplmAccessJudgeService;
import com.hustcad.plm.pdm.audit.util.TyplmAuditLogUtil;
import com.hustcad.plm.pdm.common.IPUtils;
import com.hustcad.plm.pdm.common.service.remote.LicenseRemoteService;
import com.hustcad.plm.pdm.common.service.remote.config.LicenseConfig;
import com.hustcad.plm.pdm.common.service.system.SystemConfigService;
import com.hustcad.plm.pdm.common.util.CommonUtil;
import com.hustcad.plm.pdm.enumeration.model.dto.EnumerationValueDTO;
import com.hustcad.plm.pdm.enumeration.service.TyplmEnumerationService;
import com.hustcad.plm.pdm.file.model.entity.PdmFile;
import com.hustcad.plm.pdm.file.service.PdmFileServiceExt;
import com.hustcad.plm.pdm.folder.service.TyplmCabinetService;
import com.hustcad.plm.pdm.preference.util.TyplmPreferenceValueUtil;
import com.hustcad.plm.pdm.redis.service.TyplmAsyncHandleCache;
import com.hustcad.plm.pdm.redis.service.TyplmRedisService;
import com.hustcad.plm.pdm.redislock.TyplmRedisLockService;
import com.hustcad.plm.pdm.security.entity.AuthParamDTO;
import com.hustcad.plm.pdm.security.entity.AuthenticateResultVO;
import com.hustcad.plm.pdm.security.entity.SecurityUser;
import com.hustcad.plm.pdm.security.service.AuthenticationService;
import com.hustcad.plm.pdm.security.service.CommonIntegrationService;
import com.hustcad.plm.pdm.security.service.JwtAuthentionService;
import com.hustcad.plm.pdm.security.util.JwtTokenUtil;
import com.hustcad.plm.pdm.security.utils.RedisTokenUtil;
import com.hustcad.plm.pdm.user.mapper.PdmUserMapper;
import com.hustcad.plm.pdm.user.model.constant.UserErrorCodeEnum;
import com.hustcad.plm.pdm.user.model.dto.IntegrationUserDTO;
import com.hustcad.plm.pdm.user.model.dto.PdmUserDTO;
import com.hustcad.plm.pdm.user.model.dto.UserPasswordDTO;
import com.hustcad.plm.pdm.user.model.dto.organization.PdmUserExcelDTO;
import com.hustcad.plm.pdm.user.model.dto.organization.UserAgentDTO;
import com.hustcad.plm.pdm.user.model.entity.LoginInfoDO;
import com.hustcad.plm.pdm.user.model.entity.PdmUser;
import com.hustcad.plm.pdm.user.model.entity.UserAgent;
import com.hustcad.plm.pdm.user.service.*;
import com.hustcad.plm.pdm.user.service.agent.UserAgentAdapter;
import com.hustcad.plm.pdm.user.service.agent.UserAgentDataServiceExt;
import com.hustcad.plm.pdm.user.service.agent.UserAgentService;
import com.hustcad.plm.pdm.user.service.organization.PdmUserService;
import com.hustcad.plm.pdm.user.util.TyplmUserDealUtil;
import com.ty.basic.entity.CTyEntityBaseDO;
import com.ty.basic.entity.IdentifierEntity;
import com.ty.basic.entity.PrincipalEntity;
import com.ty.basic.entity.audit.AuditLogDO;
import com.ty.basic.entity.org.OrgContainerDO;
import com.ty.basic.entity.org.OrgDO;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.exception.MessageException;
import com.ty.basic.exception.message.SystemErrorCodeEnum;
import com.ty.basic.handler.exceptionhandler.exception.ResponseCodeEnum;
import com.ty.basic.handler.exceptionhandler.exception.TyException;
import com.ty.basic.response.ResponseResult;
import com.ty.basic.service.snow.SnowflakeIdComponent;
import com.ty.basic.session.TyAccountContext;
import com.ty.basic.util.DateUtils;
import com.ty.basic.util.DownLoadFileUtils;
import com.ty.basic.util.StringUtil;
import com.ty.basic.utils.SessionUtils;
import com.ty.basic.utils.excel.converter.ExcelToList;
import com.ty.security.util.SecurityCheckUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.assertj.core.util.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Primary;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 *
 * 替换原登录逻辑 去除许可证验证逻辑
 */
@Service
@Transactional(
    rollbackFor = {Exception.class}
)
@Primary
@RefreshScope
public class MyPdmUserServiceImpl extends BaseEntityServiceImpl<PdmUserMapper, PdmUser> implements PdmUserService {
    private static final Logger log = LoggerFactory.getLogger(MyPdmUserServiceImpl.class);
    private static final String USER_ADMIN = "admin";
    private static final String ORDER_KEY_CREATESTAMP_DESC = "createstamp desc";
    private static final String KEY_ACCOUNT = "account";
    private static final String KEY_SOURCE = "source";
    private static final String KEY_DISABLED = "disabled";
    private static final String KEY_SECURITYLABELS = "securitylabels";
    private static final String KEY_FULLNAME = "fullname";
    @Autowired
    private TyplmUserService typlmUserService;
    @Autowired
    private TyplmAccessJudgeService typlmAccessJudgeService;
    @Resource
    private PdmFileServiceExt pdmFileServiceExt;
    @Resource
    private UserAgentAdapter userAgentAdapter;
    @Resource
    private UserAgentDataServiceExt userAgentDataServiceExt;
    @Resource
    private TyplmUserObjectService typlmUserObjectService;
    @Resource
    private TyplmEnumerationService typlmEnumerationService;
    @Resource
    private TyplmRedisService typlmRedisService;
    @Resource
    private TyplmRedisLockService typlmRedisLockService;
    @Resource
    private RedisTokenUtil redisTokenUtil;
    @Resource
    private JwtTokenUtil jwtTokenUtil;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private SystemConfigService systemConfigService;
    @Resource
    private TyplmOrgContainerService typlmOrgContainerService;
    @Resource
    private TyplmSeparationAdminService separationAdminService;
    @Resource
    private TyplmPrincipalService typlmPrincipalService;
    @Resource
    private TyplmAsyncHandleCache typlmAsyncHandleCache;
    @Resource
    private SnowflakeIdComponent snowflakeIdComponent;
    @Resource
    private TyplmOrgService typlmOrgService;
    @Resource
    private TyplmCabinetService typlmCabinetService;
    @Resource
    private UserAgentService userAgentService;
    @Resource
    private TyplmMemberLinkService typlmMemberLinkService;
    @Resource
    private CommonIntegrationService commonIntegrationService;
    @Resource
    private TyplmUserNewRequireService typlmUserNewRequireService;
    @Resource
    private TyplmRemoteUserService typlmRemoteUserService;
    @Resource
    private TyplmKickoutLinkService typlmKickoutLinkService;
    @Resource
    private PdmUserMapper pdmUserMapper;
    @Resource
    private TyplmObjectAliasService typlmObjectAliasService;
    @Resource(
        name = "localLicenseBackup"
    )
    private LicenseConfig.LicenseBean licenseBean;
    @Resource
    private LicenseRemoteService licenseRemoteService;
    private static final String USER_AGENT = "User-Agent";
    private static final String IP = "ip";
    @Resource
    private AuthenticationService authenticationService;
    @Resource
    private TyplmPreferenceValueUtil typlmPreferenceValueUtil;
    @Resource
    private TyLoginInfoService tyLoginInfoService;
    @Resource
    private JwtAuthentionService jwtAuthentionService;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${tysoft.password.minLength}")
    private String minLength;
    @Value("${tysoft.password.maxLength}")
    private String maxLength;
    @Value("${integreationSwitch:false}")
    private boolean integreationSwitch;
    @Value("${defaultPass}")
    private String defaultPass;
    @Value("${spring.application.version:1.0.3}")
    private String pdmVersion;
    @Value("${db.record.fetch.interval:2000}")
    private long queryInterval;
    public static final String SUCCESS = "0";
    private static final String START = "1";
    private static final String STOP = "0";
    public static final String VERIFYCODE = "verifyCode";
    public static final String VERIFYMSG = "verifyMsg";
    public static final String STATUSKEY = "status";
    @Value("${jwt.expiration}")
    private Long expiration;

    public MyPdmUserServiceImpl() {
    }

    @Transactional(
        rollbackFor = {Exception.class}
    )
    public ResponseResult userLogin(IntegrationUserDTO frontUser, BigInteger domainId, HttpServletRequest request) throws IOException, InterruptedException {
        try {
            AuthParamDTO authParamDTO = new AuthParamDTO();
            authParamDTO.setUid(frontUser.getName());
            authParamDTO.setPassword(frontUser.getPassword());
            AuthenticateResultVO authenticateResultVO = this.authenticationService.authenticate(authParamDTO, request);
            if (ObjectUtils.isNotEmpty(authenticateResultVO) && authenticateResultVO.isPass()) {
                this.typlmRedisService.delete("adapter:user:errorNumLeft:" + frontUser.getName());
                PdmUser userDataBase = this.queryUserByName(frontUser.getName());
                ResponseResult result = this.getSuccessResponseMap(request, userDataBase, frontUser.getAppID(), frontUser.getPassword());
                String redisFlagKey = "flag:compelout:key:username:";
                this.typlmRedisService.delete(redisFlagKey + frontUser.getName());
                return result;
            } else {
                this.accountLockedIfPwdError(frontUser.getName());
                throw SystemErrorCodeEnum.USER_NOT_EXISTS.getException(new Object[0]);
            }
        } catch (Throwable var9) {
            throw var9;
        }
    }

    private void recordLoginInfo(String frontUserName, String loginIP, String appID) throws InterruptedException {
        LoginInfoDO loginInfoDO = new LoginInfoDO();
        loginInfoDO.setOid(this.snowflakeIdComponent.getInstance().nextId());
        loginInfoDO.setIp(loginIP);
        loginInfoDO.setDeviceinfo(appID);
        String dateString = DateUtils.getDateString(new Date(), "yyyy-MM-dd");
        Date loginDate = DateUtils.getDate(dateString, "yyyy-MM-dd");
        loginInfoDO.setLogintime(loginDate);
        loginInfoDO.setPerformversion(this.pdmVersion);
        loginInfoDO.setLoginname(frontUserName);
        TyplmLoggerUtil.debug(log, () -> {
            return "recordLoginInfo记录登录信息loginInfoDO为==>【{}】";
        }, () -> {
            return new Object[]{JSON.toJSONString(loginInfoDO)};
        });
        LoginInfoDO loginInfoDO1 = this.tyLoginInfoService.queryByLoginName(frontUserName, loginDate);
        if (Objects.isNull(loginInfoDO1)) {
            log.info("当前查不到活跃信息，" + this.queryInterval / 1000L + "秒后重试");
            Thread.sleep(this.queryInterval);
            loginInfoDO1 = this.tyLoginInfoService.queryByLoginName(frontUserName, loginDate);
        }

        if (Objects.nonNull(loginInfoDO1)) {
            log.info("该用户今天登录过系统，直接进行更新");
            this.tyLoginInfoService.updateLoginInfo(loginInfoDO);
        } else {
            log.info("该用户今天未登录过系统，插入记录");
            this.tyLoginInfoService.insert(loginInfoDO);
        }

    }

    @Transactional(
        rollbackFor = {Exception.class}
    )
    public ResponseResult userLogin(IntegrationUserDTO frontUser, BigInteger domainId, String integreationType, HttpServletRequest request) throws IOException, InterruptedException {
        String frontUserName = frontUser.getName();
        String frontPassword = frontUser.getPassword();
        boolean passed = this.checkIntegratedUser(frontUserName, frontPassword, integreationType);
        TyplmLoggerUtil.debug(log, () -> {
            return "userLogin调用checkIntegratedUser集成用户判断（降低圈复杂度）结果【{}】";
        }, () -> {
            return new Object[]{passed};
        });
        if (passed) {
            PdmUser userDataBase = this.queryUserByName(frontUserName);
            if (Objects.nonNull(userDataBase)) {
                String userName = userDataBase.getName();
                if (StringUtils.isNotEmpty(userName)) {
                    TyplmLoggerUtil.debug(log, () -> {
                        return "userLogin获取的用户名userName为==>【{}】";
                    }, () -> {
                        return new Object[]{userName};
                    });
                    this.isLockedAccount(userName);
                    this.typlmRedisService.delete("adapter:user:errorNumLeft:" + userName);
                }

                ResponseResult result = this.getSuccessResponseMap(request, userDataBase, frontUser.getAppID(), (String)null);
                String redisFlagKey = "flag:compelout:key:username:";
                this.typlmRedisService.delete(redisFlagKey + frontUserName);
                return result;
            } else {
                return ResponseResult.success((Object)null);
            }
        } else {
            throw SystemErrorCodeEnum.USER_NOT_EXISTS.getException(new Object[0]);
        }
    }

    private ResponseResult getSuccessResponseMap(HttpServletRequest request, PdmUser userDataBase, String appID, String realPassword) throws IOException, InterruptedException {
        if (Objects.nonNull(userDataBase)) {
            Map<String, Object> userMap = this.setToken(request, userDataBase, appID, realPassword, "PC");
            return ResponseResult.success(userMap);
        } else {
            return ResponseResult.success((Object)null);
        }
    }

    public Map<String, Object> setToken(HttpServletRequest request, PdmUser userDataBase, String appID, String realPassword, String source) throws IOException, InterruptedException {
        this.separationAdminService.batchCheckPendingApprovalUsers(Collections.singletonList(userDataBase.getOid()));
        TyplmLoggerUtil.debug(log, () -> {
            return "getSuccessResponseMap调用isAdminApi查询当前账号是否为管理员";
        }, () -> {
            return new Object[0];
        });
        boolean isAdmin = this.typlmAccessJudgeService.isAdminApi(userDataBase);
        OrgContainerDO orgContainerDO = this.typlmOrgContainerService.queryDefaultOrgContainer(userDataBase);
        userDataBase.setDomainoid(orgContainerDO.getOrgoid());
        Map<String, Object> userMap = this.getInitUserMap(userDataBase, isAdmin, orgContainerDO);
        if (realPassword != null) {
            boolean isShaPassword = realPassword.length() == 64;
            this.checkPasswordRule(userMap, realPassword, userDataBase, isShaPassword);
        }

        TyAccountContext.setUser(userDataBase);
        TyAccountContext.setBizCommonHolderMapValue("ip", SecurityCheckUtil.getIpAddr(request));
        TyAccountContext.setBizCommonHolderMapValue("User-Agent", request.getHeader("User-Agent"));
        TyplmLoggerUtil.debug(log, () -> {
            return "getSuccessResponseMap调用setTokenHeader用户登录后置处理,包括获取token，验证token和写日志";
        }, () -> {
            return new Object[0];
        });
        this.setTokenHeader(userDataBase, StringUtils.isEmpty(appID) ? source : appID, IPUtils.getIpAddress(request));
        return userMap;
    }

    public ResponseResult tokenLogin(String accessToken, HttpServletRequest request) throws IOException, InterruptedException {
        String username = this.jwtAuthentionService.getUserNameByToken(accessToken);
        PdmUser userDataBase = null;
        if (StringUtils.isNotEmpty(username)) {
            TyplmLoggerUtil.debug(log, () -> {
                return "tokenLogin获取的用户名username为==>【{}】";
            }, () -> {
                return new Object[]{username};
            });
            userDataBase = this.queryUserByName(username);
        }

        if (Objects.isNull(userDataBase)) {
            throw SystemErrorCodeEnum.USER_SESSION_INVALID.getException(new Object[0]);
        } else {
            return this.getSuccessResponseMap(request, userDataBase, "PC", (String)null);
        }
    }

    private boolean checkIntegratedUser(String frontUserName, String realPassword, String integreationType) {
        boolean passed = false;
        if (this.integreationSwitch && StringUtils.isNotEmpty(integreationType)) {
            JSONObject obj = new JSONObject();
            obj.put("uid", frontUserName);
            obj.put("password", realPassword);
            obj.put("integrationType", integreationType);
            AuthenticateResultVO resultVO = null;

            try {
                resultVO = this.commonIntegrationService.authenticate(obj);
                if (Objects.nonNull(resultVO)) {
                    passed = resultVO.isPass();
                }
            } catch (Exception var8) {
                throw SystemErrorCodeEnum.USER_NOT_EXISTS.getException(new Object[0]);
            }
        }

        if (TyAccountContext.isDebug()) {
            log.info("checkIntegratedUser的出参passed为<==【{}】", passed);
        }

        return passed;
    }

    private boolean isNeedUpdatePwd(String password) {
        return password == null;
    }

    public void checkPasswordRule(Map<String, Object> userMap, String realPassword, PdmUser pdmUser, boolean isShaPassword) {
        if (this.isNeedUpdatePwd(pdmUser.getPassword())) {
            userMap.put("verifyCode", 1);
            userMap.put("verifyMsg", SystemErrorCodeEnum.USER_USING_INITIAL_PASSWORD.getException(new Object[0]).getLocaleMessage());
        } else if (!isShaPassword) {
            if (this.pswMinLengthMatch(realPassword)) {
                if (this.pswMaxLengthMatch(realPassword)) {
                    if (this.passwordNotSameAsusername(pdmUser.getName(), realPassword)) {
                        if (!this.checkPswComplexity(realPassword)) {
                            userMap.put("verifyCode", SystemErrorCodeEnum.PASSWORD_COMPLEXITY_CORR.getCode());
                            userMap.put("verifyMsg", SystemErrorCodeEnum.PASSWORD_COMPLEXITY_CORR.getException(new Object[0]).getLocaleMessage());
                        }
                    } else {
                        userMap.put("verifyCode", SystemErrorCodeEnum.PASSWORD_SAME_AS_USERNAME.getCode());
                        userMap.put("verifyMsg", SystemErrorCodeEnum.PASSWORD_SAME_AS_USERNAME.getException(new Object[0]).getLocaleMessage());
                    }
                } else {
                    userMap.put("verifyCode", SystemErrorCodeEnum.PASSWORD_CHAR_CANT_EXCEED.getCode());
                    userMap.put("verifyMsg", SystemErrorCodeEnum.PASSWORD_CHAR_CANT_EXCEED.getException(new Object[0]).getLocaleMessage());
                }
            } else {
                userMap.put("verifyCode", SystemErrorCodeEnum.PASSWORD_AT_LEAST_CHAR.getCode());
                userMap.put("verifyMsg", SystemErrorCodeEnum.PASSWORD_AT_LEAST_CHAR.getException(new Object[0]).getLocaleMessage());
            }

        }
    }

    private void checkUserNameAndPassword(String userName, String password) {
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
            throw SystemErrorCodeEnum.USER_PASSWORD_NEEDED.getException(new Object[0]);
        }
    }

    private boolean passwordNotSameAsusername(String username, String password) {
        return StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password) && !username.equals(password);
    }

    private boolean pswMinLengthMatch(String password) {
        String minlengthStr = this.systemConfigService.queryConfigurationParamByKey("minlength");
        String maxlengthStr = this.systemConfigService.queryConfigurationParamByKey("maxlength");
        int minLen = 0;
        if (StringUtils.isNotEmpty(minlengthStr)) {
            minLen = Integer.parseInt(minlengthStr);
        }

        int maxLen = 0;
        if (StringUtils.isNotEmpty(maxlengthStr)) {
            maxLen = Integer.parseInt(maxlengthStr);
        }

        if (maxLen >= minLen && minLen >= Integer.parseInt(this.minLength) && maxLen <= Integer.parseInt(this.maxLength) && StringUtils.isNotEmpty(password)) {
            int len = password.length();
            return len >= minLen;
        } else {
            return true;
        }
    }

    private boolean pswMaxLengthMatch(String password) {
        String minlengthStr = this.systemConfigService.queryConfigurationParamByKey("minlength");
        String maxlengthStr = this.systemConfigService.queryConfigurationParamByKey("maxlength");
        int minLen = 0;
        if (StringUtils.isNotEmpty(minlengthStr)) {
            minLen = Integer.parseInt(minlengthStr);
        }

        int maxLen = 0;
        if (StringUtils.isNotEmpty(maxlengthStr)) {
            maxLen = Integer.parseInt(maxlengthStr);
        }

        if (maxLen >= minLen && minLen >= Integer.parseInt(this.minLength) && maxLen <= Integer.parseInt(this.maxLength) && StringUtils.isNotEmpty(password)) {
            int len = password.length();
            return len <= maxLen;
        } else {
            return true;
        }
    }

    private boolean checkPswComplexity(String password) {
        int matchCount = 0;
        String configComplexityStr = this.systemConfigService.queryConfigurationParamByKey("matchrule");
        int configComplexity = 0;
        if (StringUtils.isNotEmpty(configComplexityStr)) {
            configComplexity = Integer.parseInt(configComplexityStr);
        }

        String regEx1 = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？\\\\\\\\]";
        Pattern p = Pattern.compile(regEx1);
        Matcher m = p.matcher(password);
        if (m.find()) {
            ++matchCount;
        }

        String regEx2 = "^(?=.*[A-Z])";
        p = Pattern.compile(regEx2);
        m = p.matcher(password);
        if (m.find()) {
            ++matchCount;
        }

        String regEx3 = "^(?=.*[a-z])";
        p = Pattern.compile(regEx3);
        m = p.matcher(password);
        if (m.find()) {
            ++matchCount;
        }

        String regEx4 = "^(?=.*\\d)";
        p = Pattern.compile(regEx4);
        m = p.matcher(password);
        if (m.find()) {
            ++matchCount;
        }

        return matchCount >= configComplexity;
    }

    public PdmUser queryUserByName(String userName) {
        TyplmLoggerUtil.debug(log, () -> {
            return "queryUserByName的入参userName为==>【{}】";
        }, () -> {
            return new Object[]{userName};
        });
        Map<String, Object> param = new HashMap();
        param.put("account", userName);
        List<PdmUser> pdmUserList = this.getUserListByParams(param, true);
        if (CollectionUtils.isEmpty(pdmUserList)) {
            return null;
        } else {
            PdmUser user = (PdmUser)pdmUserList.get(0);
            if (user.getDisabled() == 1L) {
                throw SystemErrorCodeEnum.USER_DISABLED.getException(new Object[0]);
            } else {
                TyplmLoggerUtil.debug(log, () -> {
                    return "queryUserByName的出参user为<==【{}】";
                }, () -> {
                    return new Object[]{JSON.toJSONString(user)};
                });
                return user;
            }
        }
    }

    public PdmUser queryUser(String name) {
        TyplmLoggerUtil.debug(log, () -> {
            return "queryUser的入参name为==>【{}】";
        }, () -> {
            return new Object[]{name};
        });
        Map<String, Object> param = new HashMap();
        param.put("account", name);
        param.put("source", "app");
        List<PdmUser> pdmUserList = this.getUserListByParams(param, true);
        if (CollectionUtils.isEmpty(pdmUserList)) {
            return null;
        } else {
            TyplmLoggerUtil.debug(log, () -> {
                return "queryUser的 查询匹配的用户数量为<==【{}】";
            }, () -> {
                return new Object[]{pdmUserList.size()};
            });
            if (pdmUserList.size() > 1) {
                throw SystemErrorCodeEnum.USER_NOT_EXISTS.getException(new Object[0]);
            } else {
                PdmUser user = (PdmUser)pdmUserList.get(0);
                if (user.getDisabled() == 1L) {
                    throw SystemErrorCodeEnum.USER_DISABLED.getException(new Object[0]);
                } else {
                    TyplmLoggerUtil.debug(log, () -> {
                        return "queryUserByName的出参user为<==【{}】";
                    }, () -> {
                        return new Object[]{JSON.toJSONString(user)};
                    });
                    return user;
                }
            }
        }
    }

    public ResponseResult userLoginFromTs(JSONObject json, HttpServletRequest request) throws IOException, InterruptedException {
        IntegrationUserDTO user = new IntegrationUserDTO();
        JSONObject input = json.getJSONObject("input");
        ResponseResult result;
        if (null != input) {
            user.setName(input.getString("userID"));
            user.setPassword(input.getString("passWord"));
            user.setAppID("TS");

            try {
                //todo AD域集成参数填写到 ""中
                result = this.userLogin(user, (BigInteger)null,"", request);
                if (result.isSuccess()) {
                    JSONObject resultData = (JSONObject)result.getData();
                    result.setData(resultData.get("userOid"));
                }
            } catch (Exception var7) {
                Exception exception = var7;
                this.addErrorAuditLog(request, user, exception);
                throw var7;
            }
        } else {
            result = ResponseResult.fail(SystemErrorCodeEnum.REQUIRED_REQUEST_BODY_IS_MISSING);
        }

        return result;
    }

    private void addErrorAuditLog(HttpServletRequest request, IntegrationUserDTO user, Exception exception) {
        AuditLogDO auditLogDO = new AuditLogDO();
        UserDO userDO = this.typlmUserService.queryUserByName(user.getName());
        if (userDO != null) {
            auditLogDO.setCreatoroid(userDO.getOid());
            auditLogDO.setCreatorotype(userDO.getOtype());
            auditLogDO.setContaineroid(userDO.getContaineroid());
            auditLogDO.setContainerotype(userDO.getContainerotype());
            auditLogDO.setObjoid(userDO.getOid());
            auditLogDO.setObjotype(userDO.getOtype());
            auditLogDO.setUsername(userDO.getFullname() + "(" + userDO.getName() + ")");
        } else {
            auditLogDO.setCreatoroid(BigInteger.ZERO);
            auditLogDO.setCreatorotype(user.getOtype());
            auditLogDO.setObjotype(user.getOtype());
            auditLogDO.setUsername(user.getName());
        }

        auditLogDO.setTargetname(user.getName());
        TyAccountContext.setBizCommonHolderMapValue("ip", SecurityCheckUtil.getIpAddr(request));
        TyAccountContext.setBizCommonHolderMapValue("User-Agent", request.getHeader("User-Agent"));
        TyplmAuditLogUtil.errorInfo(LogEventEnum.LOGIN, auditLogDO, exception);
    }

    public void isLockedAccount(String name) {
        String key = "adapter:user:errorNumLeft:" + name;
        String count = this.typlmRedisService.getString(key);
        if (!StringUtils.isBlank(count)) {
            if (!StringUtil.isDigits(count) || Integer.parseInt(count) <= 0) {
                int leftTime = this.typlmRedisService.getExpireTime(key, TimeUnit.SECONDS).intValue();
                int min = leftTime / 60;
                int seconds = leftTime % 60;
                throw SystemErrorCodeEnum.USER_ACCOUNT_LOCKED.getException(new Object[]{min, seconds});
            }
        }
    }

    public boolean checkPassword(PdmUser pdmUser, String frontPassword) {
        boolean checkResult = false;
        String truePassword = pdmUser.getPassword();
        if (truePassword != null && !this.passwordEncoder.matches(frontPassword, truePassword)) {
            String pwd = frontPassword;
            if (StringUtils.isNotBlank(pdmUser.getExt5())) {
                pwd = SecureUtil.md5(pwd + pdmUser.getExt5());
                pdmUser.setExt5((String)null);
            }

            if (truePassword.equals(pwd)) {
                checkResult = true;
                pdmUser.setPassword(this.passwordEncoder.encode(frontPassword));
                this.updateuser(pdmUser);
            }
        } else {
            checkResult = true;
        }

        if (TyAccountContext.isDebug()) {
            log.info("checkPassword的出参checkResult为<==【{}】", checkResult);
        }

        return checkResult;
    }

    public void accountLockedIfPwdError(String userName) {
        int retryTimes = 0;
        String retryTimesStr = this.systemConfigService.queryConfigurationParamByKey("retrytimes");
        if (StringUtils.isNotEmpty(retryTimesStr)) {
            retryTimes = Integer.parseInt(retryTimesStr);
        }

        int locktime = 0;
        String locktimeStr = this.systemConfigService.queryConfigurationParamByKey("locktime");
        if (StringUtils.isNotEmpty(locktimeStr)) {
            locktime = Integer.parseInt(locktimeStr);
        }

        int timeScope = 0;
        String timeScopeStr = this.systemConfigService.queryConfigurationParamByKey("timescope");
        if (StringUtils.isNotEmpty(timeScopeStr)) {
            timeScope = Integer.parseInt(timeScopeStr);
        }

        String key = "adapter:user:errorNumLeft:" + userName;
        String lockKey = "adapter:lock:userRedis:leftLoginNumeber:" + userName;
        this.typlmRedisLockService.lock(lockKey);

        try {
            if (this.typlmRedisService.exists(key)) {
                int leftTimes = Integer.parseInt(this.typlmRedisService.getString(key)) - 1;
                if (leftTimes <= 0) {
                    this.typlmRedisService.setString(key, leftTimes, TimeUnit.MINUTES.toMillis((long)locktime));
                    int time = this.typlmRedisService.getExpireTime(key, TimeUnit.SECONDS).intValue();
                    int min = time / 60;
                    int seconds = time % 60;
                    throw SystemErrorCodeEnum.USER_ACCOUNT_LOCKED.getException(new Object[]{min, seconds});
                } else {
                    this.typlmRedisService.setString(key, Integer.toString(leftTimes));
                    throw SystemErrorCodeEnum.USER_PASSWORD_ERROR.getException(new Object[]{leftTimes, locktime});
                }
            } else {
                this.typlmRedisService.setString(key, retryTimes - 1, TimeUnit.MINUTES.toMillis((long)timeScope));
                throw SystemErrorCodeEnum.USER_PASSWORD_ERROR.getException(new Object[]{retryTimes - 1, locktime});
            }
        } finally {
            this.typlmRedisLockService.unlock(lockKey);
        }
    }

    private void setTokenHeader(PdmUser pdmUser, String appID, String loginIP) throws InterruptedException {
//        LicenseConfig.LicenseBean verifyBean;
//        try {
//            verifyBean = this.licenseBean.initLicenseBean(this.licenseRemoteService);
//        } catch (Exception var7) {
//            Exception e = var7;
//            log.error(e.getLocalizedMessage());
//            throw SystemErrorCodeEnum.CONSUMER_LICENSE_ERROR.getException(new Object[]{e.getLocalizedMessage()});
//        }
//
//        if (!ObjectUtils.isEmpty(verifyBean)) {
//            Integer onlineUser = this.getOnlineUserDistinct();
//            Integer consumerAmount = verifyBean.getConsumerAmount();
//            if (onlineUser.compareTo(consumerAmount) >= 0) {
//                log.error("校验License失败：失败原因：用户节点数超出");
//                throw SystemErrorCodeEnum.CONSUMER_LICENSE_ERROR.getException(new Object[]{"用户节点数超出"});
//            }
//        }

        SecurityUser securityUser = new SecurityUser(pdmUser.getName());
        TyplmLoggerUtil.debug(log, () -> {
            return "setTokenHeader调用generateToken生成token字段";
        }, () -> {
            return new Object[0];
        });
        String token = this.jwtTokenUtil.generateToken(securityUser);
        this.checkAccountLogin(pdmUser, token, appID, loginIP);
        this.typlmRedisService.setString("app_" + securityUser.getUsername(), token);
        this.recordLoginInfo(pdmUser.getName(), loginIP, appID);
        TyplmAuditLogUtil.info(pdmUser.getOid(), pdmUser.getOtype(), LogEventEnum.LOGIN);
        this.jwtTokenUtil.setTokenHeader(token);
    }

    private void checkAccountLogin(PdmUser pdmUser, String token, String appID, String loginIP) {
        String name = pdmUser.getName();
        if (StringUtils.isNotEmpty(name)) {
            TyplmLoggerUtil.debug(log, () -> {
                return "checkAccountLogin的入参name为==>【{}】";
            }, () -> {
                return new Object[]{name};
            });
            Map<String, Object> preferenceMap = this.typlmPreferenceValueUtil.readPreferenceValueByKeywords(Lists.newArrayList(new String[]{"ExclusiveLogin"}));
            String exclusiveLogin = "";
            if (CollUtil.isNotEmpty(preferenceMap)) {
                exclusiveLogin = (String)preferenceMap.get("ExclusiveLogin");
            }

            String redisTokenKeyPrefix = this.getRedisTokenKeyPrefix(name, appID);
            String redisTokenKey = redisTokenKeyPrefix + ":" + loginIP + ":" + token;
            String fullName = pdmUser.getFullname();
            if (StringUtils.isEmpty(fullName)) {
                fullName = pdmUser.getName();
            }

            String redisValue = appID + ":" + loginIP + ":" + fullName;
            String redisKey;
            if (exclusiveLogin.equalsIgnoreCase("on")) {
                redisKey = this.typlmKickoutLinkService.findKickOutAppIDByAppID(appID);
                String deleteFlagKeyPatternPrefix = "adapter:user:token:";
                this.dealExcludeLoginToken(name, redisKey, deleteFlagKeyPatternPrefix);
            }

            redisKey = "adapter:user:token:" + redisTokenKey;
            this.typlmRedisService.setString(redisKey, redisValue, TimeUnit.MINUTES.toMillis(this.expiration));
        }

    }

    private void dealExcludeLoginToken(String name, String kickOutAppIDSByAppID, String deleteFlagKeyPatternPrefix) {
        if (StringUtils.isNotEmpty(kickOutAppIDSByAppID)) {
            String[] kickOutAppIDByAppIDArr = kickOutAppIDSByAppID.split(",");
            List<String> allRedisKeys = new ArrayList();
            String[] var6 = kickOutAppIDByAppIDArr;
            int var7 = kickOutAppIDByAppIDArr.length;

            for(int var8 = 0; var8 < var7; ++var8) {
                String kickOutAppID = var6[var8];
                String kickOutTokenKeyPattern = this.getRedisTokenKeyPrefix(name, kickOutAppID);
                List<String> redisKeys = this.typlmRedisService.getRedisKeys(deleteFlagKeyPatternPrefix + kickOutTokenKeyPattern + "*");
                if (CollUtil.isNotEmpty(redisKeys)) {
                    allRedisKeys.addAll(redisKeys);
                }
            }

            if (CollUtil.isNotEmpty(allRedisKeys)) {
                String tokenListStr = String.join(",", allRedisKeys);
                String redisFlagKey = "flag:kickout:key:username:" + name;
                this.typlmRedisService.setString(redisFlagKey, tokenListStr, TimeUnit.MINUTES.toMillis(this.expiration));
            }
        }

    }

    private String getRedisTokenKeyPrefix(String username, String appID) {
        String appIDHead = StringUtils.isEmpty(appID) ? "" : appID;
        return username + ":" + appIDHead;
    }

    private @NotNull Map<String, Object> getInitUserMap(PdmUser pdmUser, boolean isAdmin, OrgContainerDO orgContainerDO) {
        Map<String, Object> userMap = new JSONObject();
        userMap.put("userOid", pdmUser.getOid());
        userMap.put("userOtype", pdmUser.getOtype());
        userMap.put("isAdmin", isAdmin);
        userMap.put("userName", pdmUser.getName());
        userMap.put("userFullName", pdmUser.getFullname());
        userMap.put("systemDomainOId", orgContainerDO.getOrgoid());
        userMap.put("systemDomainOtype", orgContainerDO.getOrgotype());
        userMap.put("containerOid", orgContainerDO.getOid());
        userMap.put("containerOtype", orgContainerDO.getOtype());
        userMap.put("userType", pdmUser.getUsertype());
        TyplmLoggerUtil.debug(log, () -> {
            return "getInitUserMap的出参userMap为<==【{}】";
        }, () -> {
            return new Object[]{JSON.toJSONString(userMap)};
        });
        return userMap;
    }

    public String getVerifyMsgByCode(int verifyCode) {
        String verifyMsg = "";
        if (String.valueOf(verifyCode).equals(SystemErrorCodeEnum.PASSWORD_AT_LEAST_CHAR.getCode())) {
            verifyMsg = SystemErrorCodeEnum.PASSWORD_AT_LEAST_CHAR.getException(new Object[0]).getLocaleMessage();
        }

        if (String.valueOf(verifyCode).equals(SystemErrorCodeEnum.PASSWORD_CHAR_CANT_EXCEED.getCode())) {
            verifyMsg = SystemErrorCodeEnum.PASSWORD_CHAR_CANT_EXCEED.getException(new Object[0]).getLocaleMessage();
        }

        if (String.valueOf(verifyCode).equals(SystemErrorCodeEnum.PASSWORD_SAME_AS_USERNAME.getCode())) {
            verifyMsg = SystemErrorCodeEnum.PASSWORD_SAME_AS_USERNAME.getException(new Object[0]).getLocaleMessage();
        }

        if (String.valueOf(verifyCode).equals(SystemErrorCodeEnum.PASSWORD_COMPLEXITY_CORR.getCode())) {
            verifyMsg = SystemErrorCodeEnum.PASSWORD_COMPLEXITY_CORR.getException(new Object[0]).getLocaleMessage();
        }

        if (String.valueOf(verifyCode).equals(SystemErrorCodeEnum.PASSWORD_NO_EQUAL.getCode())) {
            verifyMsg = SystemErrorCodeEnum.PASSWORD_NO_EQUAL.getException(new Object[0]).getLocaleMessage();
        }

        return verifyMsg;
    }

    public Boolean userLogout(HttpSession session, SessionStatus sessionStatus) {
        UserDO userDO = TyAccountContext.getUser();
        if (Objects.nonNull(userDO)) {
            TyplmAuditLogUtil.info(userDO.getOid(), userDO.getOtype(), LogEventEnum.LOGOUT);
        }

        String token = SessionUtils.getToken();
        List<String> redisKeys = this.typlmRedisService.getRedisKeys("adapter:user:token:**" + token + "*");
        String fullToken = "";
        if (CollUtil.isNotEmpty(redisKeys)) {
            fullToken = (String)redisKeys.get(0);
        }

        int index = fullToken.indexOf(this.tokenHead);
        String tokenPattern = "";
        if (index > -1) {
            tokenPattern = fullToken.substring(0, index);
        }

        this.typlmRedisService.deleteByPattern(tokenPattern + "*");
        this.typlmRedisService.delete("app_" + CommonUtil.getUser().getName());
        return true;
    }

    public void restUserPassWord(BigInteger userId, String oldPassWord, String newPassWord, String secondPassWord) {
        PdmUser user = (PdmUser)this.selectOneByOid(userId);
        if (user == null) {
            throw SystemErrorCodeEnum.USER_NOT_EXISTS.getException(new Object[0]);
        } else if (!userId.equals(CommonUtil.getUser().getOid())) {
            throw SystemErrorCodeEnum.USER_UPDATE_OTHERS_PWD.getException(new Object[0]);
        } else {
            if (user.getPassword() == null) {
                this.typlmRedisService.delete("adapter:user:errorNumLeft:" + user.getName());
            } else {
                if (!StringUtils.isNotEmpty(oldPassWord) || !StringUtils.isNotEmpty(newPassWord)) {
                    throw SystemErrorCodeEnum.PASSWORD_EMPTY_ERROR.getException(new Object[0]);
                }

                if (oldPassWord.equals(newPassWord)) {
                    throw SystemErrorCodeEnum.NEW_PASSWORD_SAME_AS_OLD_PASSWORD.getException(new Object[0]);
                }

                String shaPassword = SecureUtil.sha256(oldPassWord);
                if (!this.checkPasswordIfRight(user, shaPassword)) {
                    this.accountLockedIfPwdError(user.getName());
                } else {
                    this.typlmRedisService.delete("adapter:user:errorNumLeft:" + user.getName());
                }
            }

            this.commonPswCheck(newPassWord, secondPassWord, user);
            this.updatePasswordByUserOID(userId.toString(), this.passwordEncrypt(newPassWord));
        }
    }

    public void updatePasswordByUserOID(String userOid, String password) {
        UserPasswordDTO userPasswordDTO = new UserPasswordDTO();
        userPasswordDTO.setOid(userOid);
        userPasswordDTO.setPassword(password);
        this.typlmUserService.updatePasswordByUserOID(userPasswordDTO);
    }

    @Transactional(
        rollbackFor = {Exception.class}
    )
    public void batchDealUserPinyinByPinYinIsNull() {
        List<UserDO> userDOList = this.typlmUserService.queryUser();
        List<TyplmObjectAliasDO> pinYinDOList = new ArrayList();
        Iterator var3 = userDOList.iterator();

        while(var3.hasNext()) {
            UserDO userDO = (UserDO)var3.next();
            BigInteger userOid = userDO.getOid();
            String fullnamePinyin;
            List fullNamepinYinDOList;
            if (StringUtils.isNotBlank(userDO.getName())) {
                fullnamePinyin = TyplmPinYinUtil.getPinyinByChinese(userDO.getName());
                userDO.setNamepinyin(fullnamePinyin);
                fullNamepinYinDOList = this.typlmObjectAliasService.batchDealTyplmPinYinDO(userOid, "ty.inteplm.org.CTyUser", "ty_user;name", fullnamePinyin);
                if (CollUtil.isNotEmpty(fullNamepinYinDOList)) {
                    pinYinDOList.addAll(fullNamepinYinDOList);
                }
            }

            if (StringUtils.isNotBlank(userDO.getFullname())) {
                fullnamePinyin = TyplmPinYinUtil.getPinyinByChinese(userDO.getFullname());
                userDO.setFullnamepinyin(fullnamePinyin);
                fullNamepinYinDOList = this.typlmObjectAliasService.batchDealTyplmPinYinDO(userOid, "ty.inteplm.org.CTyUser", "ty_user;fullname", fullnamePinyin);
                if (CollUtil.isNotEmpty(fullNamepinYinDOList)) {
                    pinYinDOList.addAll(fullNamepinYinDOList);
                }
            }
        }

        if (CollUtil.isNotEmpty(userDOList)) {
            List<List<UserDO>> pieceList = CommonUtil.subObjectList(userDOList, 500);
            Iterator var9 = pieceList.iterator();

            while(var9.hasNext()) {
                List<UserDO> typlmObjectAliasDOS = (List)var9.next();
                this.pdmUserMapper.batchUpdateUserPinyin(typlmObjectAliasDOS);
            }
        }

        this.typlmObjectAliasService.batchDeletePinYinByRefvaluenameList(Lists.newArrayList(new String[]{"ty_user;name", "ty_user;fullname"}));
        if (CollUtil.isNotEmpty(pinYinDOList)) {
            this.typlmObjectAliasService.batchInsertPinyin(pinYinDOList);
        }

    }

    private boolean checkPasswordIfRight(PdmUser pdmUser, String frontPassword) {
        if (pdmUser.getPassword() != null && !this.passwordEncoder.matches(frontPassword, pdmUser.getPassword())) {
            if (StringUtils.isNotBlank(pdmUser.getExt5())) {
                frontPassword = SecureUtil.md5(frontPassword + pdmUser.getExt5());
            }

            return pdmUser.getPassword().equals(frontPassword);
        } else {
            return true;
        }
    }

    private void commonPswCheck(String newPassWord, String secondPassWord, PdmUser user) {
        if (this.pswMinLengthMatch(newPassWord)) {
            if (this.pswMaxLengthMatch(newPassWord)) {
                if (this.passwordNotSameAsusername(user.getName(), newPassWord)) {
                    if (!this.checkPswComplexity(newPassWord)) {
                        throw SystemErrorCodeEnum.PASSWORD_COMPLEXITY_CORR.getException(new Object[0]);
                    } else if (!newPassWord.equals(secondPassWord)) {
                        throw SystemErrorCodeEnum.PASSWORD_NO_EQUAL.getException(new Object[0]);
                    }
                } else {
                    throw SystemErrorCodeEnum.PASSWORD_SAME_AS_USERNAME.getException(new Object[0]);
                }
            } else {
                throw SystemErrorCodeEnum.PASSWORD_CHAR_CANT_EXCEED.getException(new Object[0]);
            }
        } else {
            throw SystemErrorCodeEnum.PASSWORD_AT_LEAST_CHAR.getException(new Object[0]);
        }
    }

    public void adminResetUserPassWord(BigInteger userId) {
        PdmUser user = (PdmUser)this.selectOneByOid(userId);
        if (user == null) {
            throw SystemErrorCodeEnum.USER_NOT_EXISTS.getException(new Object[0]);
        } else {
            TyplmLoggerUtil.debug(log, () -> {
                return "adminResetUserPassWord根据userId获取的user为==>【{}】";
            }, () -> {
                return new Object[]{JSON.toJSONString(user)};
            });
            if ("admin".equals(user.getName())) {
                throw SystemErrorCodeEnum.USER_ADMIN_RESET_SELF.getException(new Object[0]);
            } else {
                this.updatePasswordByUserOID(userId.toString(), (String)null);
                TyplmAuditLogUtil.info(user.getOid(), user.getOtype(), LogEventEnum.RESET_PASSWORD);
            }
        }
    }

    protected String passwordEncrypt(String newPassWord) {
        newPassWord = SecureUtil.sha256(newPassWord);
        return this.passwordEncoder.encode(newPassWord);
    }

    public void startUser(List<BigInteger> userIdList) {
        Iterator var2 = userIdList.iterator();

        while(var2.hasNext()) {
            BigInteger userid = (BigInteger)var2.next();
            PdmUser user = (PdmUser)this.selectOneByOid(userid);
            user.setDisabled(0L);
            this.updateuser(user);
        }

    }

    public void stopUser(List<BigInteger> userIdList) {
        Iterator var2 = userIdList.iterator();

        while(var2.hasNext()) {
            BigInteger userid = (BigInteger)var2.next();
            PdmUser user = (PdmUser)this.selectOneByOid(userid);
            user.setDisabled(1L);
            this.updateuser(user);
        }

    }

    public PdmUserDTO createUser(PdmUserDTO user) {
        TyplmUserDealUtil.checkName(user.getAccount());
        TyplmUserDealUtil.checkFullName(user.getUsername());
        if (StringUtils.isNotBlank(user.getPassword())) {
            user.setPassword(SecureUtil.sha256(user.getPassword()));
        }

        Map<String, Object> param = new HashMap();
        param.put("account", user.getAccount());
        List<PdmUser> pdmUserList = this.getUserListByParams(param, true);
        if (CollUtil.isNotEmpty(pdmUserList)) {
            throw SystemErrorCodeEnum.NO_DEFINE_VALID_EXCEPTION.getException(new Object[]{"用户已经存在"});
        } else {
            BigInteger id = this.snowflakeIdComponent.getInstance().nextId();
            user.setOid(id.toString());
            user.setOtype("ty.inteplm.org.CTyUser");
            PdmUser pdmUser = TyplmUserDealUtil.coverUserToDo(user);
            this.setDefaultFields(user, pdmUser);
            List<OrgDO> allSiteOrg = this.typlmOrgService.getAllSiteOrg();
            if (!CollectionUtils.isEmpty(allSiteOrg)) {
                OrgDO orgDO = (OrgDO)allSiteOrg.get(0);
                pdmUser.setDomainoid(orgDO.getDomainoid());
                pdmUser.setDomainotype(orgDO.getDomainotype());
            }

            List<TyplmObjectAliasDO> pinYinDOList = new ArrayList();
            String fullnamePinyin;
            List fullNamepinYinDOList;
            if (Strings.isNotBlank(pdmUser.getName())) {
                fullnamePinyin = TyplmPinYinUtil.getPinyinByChinese(pdmUser.getName());
                pdmUser.setNamepinyin(fullnamePinyin);
                fullNamepinYinDOList = this.typlmObjectAliasService.batchDealTyplmPinYinDO(id, "ty.inteplm.org.CTyUser", "ty_user;name", fullnamePinyin);
                if (CollUtil.isNotEmpty(fullNamepinYinDOList)) {
                    pinYinDOList.addAll(fullNamepinYinDOList);
                }
            }

            if (Strings.isNotBlank(pdmUser.getFullname())) {
                fullnamePinyin = TyplmPinYinUtil.getPinyinByChinese(pdmUser.getFullname());
                pdmUser.setFullnamepinyin(fullnamePinyin);
                fullNamepinYinDOList = this.typlmObjectAliasService.batchDealTyplmPinYinDO(id, "ty.inteplm.org.CTyUser", "ty_user;fullname", fullnamePinyin);
                if (CollUtil.isNotEmpty(fullNamepinYinDOList)) {
                    pinYinDOList.addAll(fullNamepinYinDOList);
                }
            }

            user = this.coverUserToDto(this.createuserByDO(pdmUser), new PdmUserDTO());
            if (CollUtil.isNotEmpty(pinYinDOList)) {
                this.typlmObjectAliasService.batchInsertPinyin(pinYinDOList);
            }

            this.typlmCabinetService.createPersonalCabinetAndSubfolder(Collections.singletonList(BeanUtil.copyProperties(user, UserDO.class, new String[0])));
            return user;
        }
    }

    private void setDefaultFields(PdmUserDTO user, PdmUser pdmUser) {
        if (null == user.getTele() || "".equals(user.getTele())) {
            pdmUser.setTelephone((String)null);
        }

        if (null == user.getBirthday() || "".equals(user.getBirthday())) {
            pdmUser.setExt2((String)null);
        }

        if (null == user.getEmail() || "".equals(user.getEmail())) {
            pdmUser.setEmail((String)null);
        }

        if (StringUtils.isNotBlank(pdmUser.getPassword())) {
            pdmUser.setPassword(this.passwordEncoder.encode(pdmUser.getPassword()));
        }

    }

    @Transactional(
        rollbackFor = {Exception.class}
    )
    public PdmUserDTO createUserInOrg(PdmUserDTO user) {
        TyplmEntityBaseUtil.checkParamNotNull(user.getOrgOid(), "orgOid");
        TyplmLoggerUtil.debug(log, () -> {
            return "createUserInOrg的入参PdmUserDTO为==>【{}】";
        }, () -> {
            return new Object[]{JSON.toJSONString(user)};
        });
        OrgDO org = this.typlmOrgService.queryOrgById(user.getOrgOid());
        if (org == null) {
            throw new TyException(Collections.singletonList(new TyException(ResponseCodeEnum.BIZ_OBJECT_NOT_FOUND, new String[]{TyplmEntityBaseUtil.getOtypeDisplayName("ty.inteplm.org.CTyOrg") + ":" + user.getOrgOid()})));
        } else {
            return this.createUserInOrg(org, this.getOrgContainerByOrg(org), user);
        }
    }

    private OrgContainerDO getOrgContainerByOrg(OrgDO org) {
        OrgContainerDO containerDO = null;
        if ("ty.inteplm.domain.CTySiteContainer".equals(org.getContainerotype())) {
            containerDO = this.typlmOrgContainerService.queryOrgContainerByOrg(org.getOid(), org.getOtype());
        } else {
            containerDO = this.typlmOrgContainerService.queryOrgContainerByOid(org.getContaineroid());
        }

        if (containerDO == null) {
            throw new TyException(Collections.singletonList(new TyException(ResponseCodeEnum.BIZ_OBJECT_NOT_FOUND, new String[]{"OrgContainer"})));
        } else {
            if (TyAccountContext.isDebug()) {
                log.info("getOrgContainerByOrg的出参containerDO为<==【{}】", JSON.toJSONString(containerDO));
            }

            return containerDO;
        }
    }

    private PdmUserDTO createUserInOrg(OrgDO org, OrgContainerDO containerDO, PdmUserDTO user) {
        TyplmEntityBaseUtil.checkParamNotNull(org, "Org");
        TyplmEntityBaseUtil.checkParamNotNull(containerDO, "OrgContainer");
        TyplmUserDealUtil.checkName(user.getAccount());
        TyplmUserDealUtil.checkFullName(user.getUsername());
        if (StringUtils.isNotBlank(user.getPassword())) {
            user.setPassword(SecureUtil.sha256(user.getPassword()));
        }

        if (StringUtils.isBlank(user.getLang())) {
            user.setLang("zh_CN");
        }

        user.setStatus("1");
        if (this.typlmUserService.checkName((BigInteger)null, user.getAccount())) {
            throw SystemErrorCodeEnum.NO_DEFINE_VALID_EXCEPTION.getException(new Object[]{"用户已经存在"});
        } else {
            BigInteger userOid = this.snowflakeIdComponent.getInstance().nextId();
            user.setOid(userOid.toString());
            user.setOtype("ty.inteplm.org.CTyUser");
            PdmUser pdmUser = TyplmUserDealUtil.coverUserToDo(user);
            this.setDefaultFields(user, pdmUser);
            pdmUser.setDomainoid(containerDO.getDomainoid());
            pdmUser.setDomainotype(containerDO.getDomainotype());
            pdmUser.setContaineroid(containerDO.getOid());
            pdmUser.setContainerotype(containerDO.getOtype());
            this.typlmPrincipalService.checkPrincipal(pdmUser);
            List<TyplmObjectAliasDO> pinYinDOList = new ArrayList();
            String fullnamePinyin;
            List fullNamepinYinDOList;
            if (Strings.isNotBlank(pdmUser.getName())) {
                fullnamePinyin = TyplmPinYinUtil.getPinyinByChinese(pdmUser.getName());
                pdmUser.setNamepinyin(fullnamePinyin);
                fullNamepinYinDOList = this.typlmObjectAliasService.batchDealTyplmPinYinDO(userOid, "ty.inteplm.org.CTyUser", "ty_user;name", fullnamePinyin);
                if (CollUtil.isNotEmpty(fullNamepinYinDOList)) {
                    pinYinDOList.addAll(fullNamepinYinDOList);
                }
            }

            if (Strings.isNotBlank(pdmUser.getFullname())) {
                fullnamePinyin = TyplmPinYinUtil.getPinyinByChinese(pdmUser.getFullname());
                pdmUser.setFullnamepinyin(fullnamePinyin);
                fullNamepinYinDOList = this.typlmObjectAliasService.batchDealTyplmPinYinDO(userOid, "ty.inteplm.org.CTyUser", "ty_user;fullname", fullnamePinyin);
                if (CollUtil.isNotEmpty(fullNamepinYinDOList)) {
                    pinYinDOList.addAll(fullNamepinYinDOList);
                }
            }

            user = this.coverUserToDto(this.createuserByDO(pdmUser), new PdmUserDTO());
            if (CollUtil.isNotEmpty(pinYinDOList)) {
                this.typlmObjectAliasService.batchInsertPinyin(pinYinDOList);
            }

            UserDO userDO = this.typlmUserService.queryUserByKey(pdmUser.getOid());
            this.typlmCabinetService.createPersonalCabinetAndSubfolder(Collections.singletonList(userDO));
            if (org.getOid().equals(containerDO.getOrgoid())) {
                this.typlmMemberLinkService.addParentForPrincipal(Collections.singletonList(org), userDO);
            } else {
                OrgDO containerOrg = this.typlmOrgService.queryOrgByKey(containerDO.getOrgoid());
                this.typlmMemberLinkService.addParentForPrincipal(Arrays.asList(org, containerOrg), userDO);
            }

            if (TyAccountContext.isDebug()) {
                log.info("createUserInOrg的出参user为<==【{}】", JSON.toJSONString(user));
            }

            return user;
        }
    }

    public PdmUserDTO modifyUser(PdmUserDTO user) {
        this.validatePhoneNumber(user.getTele());
        this.validateEmail(user.getEmail());
        this.validateBirth(user.getBirthday());
        BigInteger userid = new BigInteger(user.getOid());
        PdmUser userDO = (PdmUser)this.selectOneByOid(userid);
        userDO.setFullname(user.getUsername());
        userDO.setEmail(user.getEmail());
        userDO.setTelephone(user.getTele());
        userDO.setExt1(user.getSex());
        userDO.setExt3(user.getPhoto());
        userDO.setSecuritylabels(user.getSecuritylabels());
        userDO.setLang(user.getLang());
        List<TyplmObjectAliasDO> pinYinDOList = new ArrayList();
        String fullnamePinyin = "";
        if (Strings.isNotBlank(userDO.getFullname())) {
            fullnamePinyin = TyplmPinYinUtil.getPinyinByChinese(userDO.getFullname());
            userDO.setFullnamepinyin(fullnamePinyin);
            List<TyplmObjectAliasDO> fullNamepinYinDOList = this.typlmObjectAliasService.batchDealTyplmPinYinDO(userid, "ty.inteplm.org.CTyUser", "ty_user;fullname", fullnamePinyin);
            if (CollUtil.isNotEmpty(fullNamepinYinDOList)) {
                pinYinDOList.addAll(fullNamepinYinDOList);
            }
        }

        PdmUser updateUser = this.updateuser(userDO);
        this.typlmObjectAliasService.batchDeletePinYinListByObjAndRefvaluename(Lists.newArrayList(new BigInteger[]{userid}), "ty.inteplm.org.CTyUser", "ty_user;fullname");
        if (CollUtil.isNotEmpty(pinYinDOList)) {
            this.typlmObjectAliasService.batchInsertPinyin(pinYinDOList);
        }

        return this.coverUserToDto(updateUser, new PdmUserDTO());
    }

    private boolean validateBirth(String birth) {
        if (StringUtils.isEmpty(birth)) {
            return false;
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = null;

            try {
                date = sdf.parse(birth);
                Date now = sdf.parse(sdf.format(new Date()));
                if (date.after(now)) {
                    throw UserErrorCodeEnum.BIRTHDAY_LATER_THAN_CURRENT.getException(new Object[0]);
                } else {
                    return true;
                }
            } catch (ParseException var5) {
                ParseException e = var5;
                log.error("", e);
                throw UserErrorCodeEnum.DATE_FORMAT_INPUT_ERROR.getException(new Object[0]);
            }
        }
    }

    private boolean validateEmail(String email) {
        if (StringUtils.isEmpty(email)) {
            return false;
        } else {
            Pattern pattern = Pattern.compile("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$", 2);
            Matcher matcher = pattern.matcher(email);
            if (!matcher.matches()) {
                throw UserErrorCodeEnum.EMAIL_FORMAT_INPUT_ERROR.getException(new Object[]{email});
            } else {
                return true;
            }
        }
    }

    private boolean validatePhoneNumber(String phoneNumber) {
        if (StringUtils.isEmpty(phoneNumber)) {
            return false;
        } else if (phoneNumber.matches("^[1][3-9][0-9]{9}$")) {
            return true;
        } else {
            throw UserErrorCodeEnum.PHONE_FORMAT_INPUT_ERROR.getException(new Object[]{phoneNumber});
        }
    }

    public Map<String, Object> deleteUserByList(List<BigInteger> userIdList) {
        if (CollUtil.isEmpty(userIdList)) {
            throw SystemErrorCodeEnum.ARGUMENT_NONE.getException(new Object[]{"用户"});
        } else {
            List<PdmUserDTO> pdmUserDTOList = this.getUserListByIds(userIdList);
            Map<String, Object> messageMap = new HashMap();

            for(int i = 0; i < pdmUserDTOList.size(); ++i) {
                PdmUserDTO pdmUserDTO = (PdmUserDTO)pdmUserDTOList.get(i);
                List<String> idList = new ArrayList();
                idList.add(pdmUserDTO.getOid());
                Map<String, List<UserAgentDTO>> listMap = this.userAgentAdapter.selectAgentByUserOid(idList);
                if (CollUtil.isNotEmpty(listMap)) {
                    messageMap.putAll(listMap);
                } else {
                    List<UserAgent> userAgents = this.userAgentDataServiceExt.selectAgentByUserOid(BigInteger.valueOf(Long.parseLong(pdmUserDTO.getOid())));
                    userAgents.forEach((userAgent) -> {
                        this.userAgentAdapter.deleteUserAgent(userAgent.getOid());
                    });
                    PdmFile pdmFile = new PdmFile();
                    pdmFile.setParentId(new BigInteger(pdmUserDTO.getOid()));
                    pdmFile.setParentType(((PdmUserDTO)pdmUserDTOList.get(i)).getOtype());
                    List<PdmFile> pdmFileList = this.pdmFileServiceExt.queryPdmFileList(pdmFile);
                    this.deleteSignFile(pdmFileList);
                    List<BigInteger> ids = new ArrayList();
                    ids.add(new BigInteger(pdmUserDTO.getOid()));
                    TyplmAuditLogUtil.info(pdmUserDTO.getOid(), "ty.inteplm.org.CTyUser", LogEventEnum.DELETE_OBJECT);

                    try {
                        this.deletuserByListWithCache(ids);
                    } catch (Exception var13) {
                        Exception e = var13;
                        log.error("用户{}删除失败：", pdmUserDTO.getUsername() + "(" + pdmUserDTO.getAccount() + ")", e);
                        TyplmAuditLogUtil.errorInfo(pdmUserDTO.getOid(), pdmUserDTO.getOtype(), LogEventEnum.DELETE_OBJECT, e);
                        throw UserErrorCodeEnum.DELETE_USER_FAIL.getException(new Object[0]);
                    }

                    TyplmAuditLogUtil.sendCollectInfo();
                    messageMap.put("0" + pdmUserDTO.getUsername() + "(" + pdmUserDTO.getAccount() + ")删除成功!", pdmUserDTO.getOid());
                }
            }

            this.typlmUserObjectService.deleteByUserOidList(userIdList);
            return messageMap;
        }
    }

    private void deleteSignFile(List<PdmFile> pdmFileList) {
        Iterator var2 = pdmFileList.iterator();

        while(var2.hasNext()) {
            PdmFile pdmFile1 = (PdmFile)var2.next();
            BigInteger file1Oid = pdmFile1.getOid();

            try {
                this.pdmFileServiceExt.deletePdmFile(file1Oid);
            } catch (Exception var6) {
                Exception exception = var6;
                log.error("", exception);
            }
        }

    }

    public List<PdmUserDTO> getUserListByIds(List<BigInteger> idlist) {
        List<PdmUser> pdmUserList = this.selectByOids(idlist);
        List<PdmUserDTO> list = new ArrayList();
        this.getAgentInfo(pdmUserList, idlist, list);
        TyplmLoggerUtil.debug(log, () -> {
            return "getUserListByIds的出参list为<==【{}】";
        }, () -> {
            return new Object[]{list.size()};
        });
        return list;
    }

    private void getAgentInfo(List<PdmUser> pdmuserList, Collection<BigInteger> idList, List<PdmUserDTO> list) {
        Map<BigInteger, PdmUserDTO> map = this.userAgentService.getUserIsAgent(idList);
        Iterator var5 = pdmuserList.iterator();

        while(var5.hasNext()) {
            PdmUser pdmUser = (PdmUser)var5.next();
            PdmUserDTO pdmUserDTO = new PdmUserDTO();
            PdmUserDTO pdmUserAgentDTO = (PdmUserDTO)map.get(pdmUser.getOid());
            if (ObjectUtils.isEmpty(pdmUserAgentDTO)) {
                pdmUserDTO.setIsAgent(false);
            } else {
                pdmUserDTO = pdmUserAgentDTO;
                if (Boolean.TRUE.equals(pdmUserDTO.getIsAgent())) {
                    pdmUserDTO.setAgentName(pdmUserAgentDTO.getUsername() + "(" + pdmUserAgentDTO.getAccount() + ")");
                }
            }

            pdmUserDTO = this.coverUserToDto(pdmUser, pdmUserDTO);
            list.add(pdmUserDTO);
        }

    }

    public PdmUser getUserByOid(BigInteger oid) {
        return (PdmUser)this.selectOneByOid(oid);
    }

    public PageInfo<PdmUserDTO> getUserPageByParams(Map<String, Object> params, Integer pageNum, Integer pageSize) {
        Example example = new Example(PdmUser.class, true, true);
        Example.Criteria orCriteria = example.createCriteria();
        Example.Criteria andCriteria = example.createCriteria();
        this.buildCriteria(params, orCriteria, andCriteria);
        example.and(andCriteria);
        Example.Criteria disabledCriteria = example.createCriteria();
        disabledCriteria.andEqualTo("disabled", 0L);
        example.and(disabledCriteria);
        example.setOrderByClause("createstamp desc");
        PageInfo<PdmUser> page = this.simpleQueryPageByExample(example, pageNum, pageSize);
        List<BigInteger> idList = (List)page.getList().stream().map(CTyEntityBaseDO::getOid).collect(Collectors.toList());
        List<PdmUser> pdmUserList = page.getList();
        List<PdmUserDTO> list = new ArrayList();
        this.getAgentInfo(pdmUserList, idList, list);
        PageInfo<PdmUserDTO> newPage = new PageInfo(list);
        newPage.setTotal(page.getTotal());
        TyplmLoggerUtil.debug(log, () -> {
            return "getUserPageByParams的出参newPage为<==【{}】";
        }, () -> {
            return new Object[]{JSON.toJSONString(newPage)};
        });
        return newPage;
    }

    private void buildCriteria(Map<String, Object> params, Example.Criteria orCriteria, Example.Criteria andCriteria) {
        if (CollUtil.isNotEmpty(params)) {
            Iterator var4 = params.entrySet().iterator();

            while(var4.hasNext()) {
                Map.Entry<String, Object> key = (Map.Entry)var4.next();
                String value = key.getValue().toString();
                String keyItem = (String)key.getKey();
                this.excludeUser(params, andCriteria, keyItem);
                if (StringUtils.isNotEmpty(value)) {
                    this.switchKeyItem(keyItem, value, orCriteria, andCriteria);
                }
            }
        }

    }

    private void excludeUser(Map<String, Object> params, Example.Criteria andCriteria, String keyItem) {
        if ("exIDs".equals(keyItem)) {
            Object exIds = params.get("exIDs");
            if (ArrayList.class.equals(exIds.getClass())) {
                List<String> arrIds = JSON.parseArray(exIds.toString(), String.class);
                List<BigInteger> ids = new ArrayList();
                Iterator var7 = arrIds.iterator();

                while(var7.hasNext()) {
                    Object id = var7.next();
                    ids.add(new BigInteger(id.toString()));
                }

                andCriteria.andNotIn("oid", ids);
            }
        }

    }

    private void switchKeyItem(String keyItem, String value, Example.Criteria orCriteria, Example.Criteria andCriteria) {
        switch (keyItem) {
            case "securitylabels":
                Map<String, Map<String, String>> enabledEnumItemsMap = this.typlmEnumerationService.getEnabledEnumItemsMap(Lists.newArrayList(new String[]{"SecurityLabels"}));
                Map<String, String> securityLabelsMap = (Map)ObjectUtils.defaultIfNull(enabledEnumItemsMap.get("SecurityLabels"), new HashMap());
                List<String> collect = new ArrayList(securityLabelsMap.values());
                List<String> label = new ArrayList();
                if (collect.contains(value)) {
                    int index = collect.indexOf(value);

                    for(int i = index; i < collect.size(); ++i) {
                        label.add(collect.get(i));
                    }

                    andCriteria.andIn("securitylabels", label);
                } else {
                    andCriteria.andIn("securitylabels", ObjectUtils.isNotEmpty(collect) ? Lists.newArrayList(new String[]{(String)collect.get(0)}) : Lists.newArrayList(new String[]{"null"}));
                }
                break;
            case "securitylabelsAccuracy":
                orCriteria.orEqualTo("securitylabels", value);
                break;
            case "account":
                orCriteria.orCondition("upper(name) like ", "%" + value.toUpperCase(Locale.ROOT) + "%");
                orCriteria.orLike("fullname", "%" + value + "%");
                orCriteria.orLike("namepinyin", TyplmUserDealUtil.dealPinyinQuery(value));
                orCriteria.orLike("fullnamepinyin", TyplmUserDealUtil.dealPinyinQuery(value));
                break;
            case "status":
                if ("1".equals(value)) {
                    orCriteria.orEqualTo("disabled", 0);
                }

                if ("0".equals(value)) {
                    orCriteria.orEqualTo("disabled", 1);
                }
                break;
            case "username":
                orCriteria.orLike("fullname", "%" + value + "%");
                break;
            case "sex":
                orCriteria.orEqualTo("ext1", value);
                break;
            case "tele":
                orCriteria.orLike("telephone", "%" + value + "%");
                break;
            case "oid":
                orCriteria.orEqualTo("oid", new BigInteger(value));
        }

    }

    public List<PdmUserDTO> getUserListByParams(Map<String, Object> params) {
        return this.convertUserListToDto(this.getUserListByParam(params));
    }

    private List<PdmUserDTO> convertUserListToDto(List<PdmUser> list) {
        return ObjectUtils.isEmpty(list) ? Collections.emptyList() : (List)list.stream().map((item) -> {
            return this.coverUserToDto(item, new PdmUserDTO());
        }).collect(Collectors.toList());
    }

    public PdmUserDTO coverUserToDto(PdmUser pdmUser, PdmUserDTO pdmUserDTO) {
        BeanUtil.copyProperties(pdmUser, pdmUserDTO, new String[0]);
        BigInteger bid = pdmUser.getOid();
        String btype = pdmUser.getOtype();
        PrincipalEntity principalEntity = new PrincipalEntity(bid, btype);
        List<PrincipalEntity> outParent = this.typlmPrincipalService.getOneOutParentOrg(principalEntity);
        if (CollUtil.isNotEmpty(outParent)) {
            String orgIds = (String)outParent.stream().map(CTyEntityBaseDO::getOid).map(BigInteger::toString).collect(Collectors.joining(","));
            String orgNames = (String)outParent.stream().map(CTyEntityBaseDO::getName).collect(Collectors.joining(","));
            pdmUserDTO.setOrganizationId(orgIds);
            pdmUserDTO.setOrganizationDisplay(orgNames);
        } else {
            pdmUserDTO.setOrganizationId((String)null);
            pdmUserDTO.setOrganizationDisplay((String)null);
        }

        pdmUserDTO.setDesc(pdmUser.getDescription());
        if (pdmUser.getDisabled() == 0L) {
            pdmUserDTO.setStatus("1");
        }

        if (pdmUser.getDisabled() == 1L) {
            pdmUserDTO.setStatus("0");
        }

        pdmUserDTO.setSex(pdmUser.getExt1());
        pdmUserDTO.setBirthday(pdmUser.getExt2());
        pdmUserDTO.setPhoto(pdmUser.getExt3());
        pdmUserDTO.setUsername(pdmUser.getFullname());
        pdmUserDTO.setAccount(pdmUser.getName());
        pdmUserDTO.setOid(pdmUser.getOid() == null ? null : pdmUser.getOid().toString());
        pdmUserDTO.setTele(pdmUser.getTelephone());
        pdmUserDTO.setCreatestamp(pdmUser.getCreatestamp());
        pdmUserDTO.setUpdatestamp(pdmUser.getUpdatestamp());
        pdmUserDTO.setPassword((String)null);
        if (!TyplmEntityBaseUtil.isEmptyOid(pdmUser.getContaineroid())) {
            CTyEntityBaseDO contaienr = CommonUtil.getEntity(new IdentifierEntity(pdmUser.getContaineroid(), pdmUser.getContainerotype()));
            pdmUserDTO.setContaineroid(pdmUser.getContaineroid());
            pdmUserDTO.setContainerotype(pdmUser.getContainerotype());
            pdmUserDTO.setContextName(contaienr.getName());
        }

        pdmUserDTO.setLang(pdmUser.getLang());
        TyplmLoggerUtil.debug(log, () -> {
            return "coverUserToDto的出参pdmUserDTO为<==【{}】";
        }, () -> {
            return new Object[]{JSON.toJSONString(pdmUserDTO)};
        });
        return pdmUserDTO;
    }

    public Map<BigInteger, PdmUser> getUserMapByUserCollection(Collection<BigInteger> userCollection) {
        List<PdmUser> pdmUserList = this.getUserListByOids(userCollection);
        return (Map)pdmUserList.stream().collect(Collectors.toMap(CTyEntityBaseDO::getOid, (user) -> {
            return user;
        }));
    }

    public HashMap<String, List<PdmUserExcelDTO>> importUser(MultipartFile multipartFile) {
        Map<String, String> fieldMap = ExcelToList.getExcelPropertySettingMapByClass(PdmUserExcelDTO.class);
        HashMap<String, List<PdmUserExcelDTO>> result = new HashMap();
        new ArrayList();
        List<PdmUserExcelDTO> successList = new ArrayList();
        List<PdmUserExcelDTO> errorList = new ArrayList();

        List list;
        try {
            list = ExcelToList.excelToList(multipartFile, 0, PdmUserDTO.class, fieldMap);
        } catch (Exception var10) {
            Exception e = var10;
            log.error("Excel文件解析失败！失败原因：" + e);
            throw SystemErrorCodeEnum.EXCEL_READ_EXCEPTION.getException(new Object[]{"Excel文件"});
        }

        this.batchCheckSecurityLabel(list);
        Iterator var12 = list.iterator();

        while(var12.hasNext()) {
            PdmUserDTO pdmUserDTO = (PdmUserDTO)var12.next();

            try {
                TyplmUserDealUtil.validatePdmUserDTO(pdmUserDTO);
                this.createUser(pdmUserDTO);
                successList.add(this.coverUserToExcelDTO(pdmUserDTO, ""));
            } catch (Exception var11) {
                Exception e = var11;
                log.error("创建用户失败失败！失败原因：" + e);
                errorList.add(this.coverUserToExcelDTO(pdmUserDTO, ObjectUtils.isNotEmpty(e.getMessage()) ? e.getMessage() : e.toString()));
            }
        }

        result.put("successList", successList);
        result.put("errorList", errorList);
        TyplmLoggerUtil.debug(log, () -> {
            return "importUser的出参result为<==【{}】";
        }, () -> {
            return new Object[]{JSON.toJSONString(result)};
        });
        return result;
    }

    public HashMap<String, List<PdmUserExcelDTO>> importUserInOrg(BigInteger orgOid, MultipartFile multipartFile) {
        TyplmEntityBaseUtil.checkParamNotNull(orgOid, "orgOid");
        OrgDO org = this.typlmOrgService.queryOrgById(orgOid);
        if (org == null) {
            throw new TyException(Collections.singletonList(new TyException(ResponseCodeEnum.BIZ_OBJECT_NOT_FOUND, new String[]{TyplmEntityBaseUtil.getOtypeDisplayName("ty.inteplm.org.CTyOrg") + ":" + orgOid})));
        } else {
            OrgContainerDO containerDO = this.getOrgContainerByOrg(org);
            Map<String, String> fieldMap = ExcelToList.getExcelPropertySettingMapByClass(PdmUserExcelDTO.class);
            HashMap<String, List<PdmUserExcelDTO>> result = new HashMap();
            new ArrayList();
            List<PdmUserExcelDTO> successList = new ArrayList();
            List<PdmUserExcelDTO> errorList = new ArrayList();

            List list;
            try {
                list = ExcelToList.excelToList(multipartFile, 0, PdmUserDTO.class, fieldMap);
            } catch (Exception var15) {
                Exception e = var15;
                log.error("Excel文件解析失败！失败原因：" + e);
                throw SystemErrorCodeEnum.EXCEL_READ_EXCEPTION.getException(new Object[]{"Excel文件"});
            }

            this.batchCheckSecurityLabel(list);
            Iterator var17 = list.iterator();

            while(var17.hasNext()) {
                PdmUserDTO pdmUserDTO = (PdmUserDTO)var17.next();
                PdmUserExcelDTO excelDTO = this.coverUserToExcelDTO(pdmUserDTO, "");

                try {
                    TyplmUserDealUtil.validatePdmUserDTO(pdmUserDTO);
                    this.typlmUserNewRequireService.createUserInOrgForImport(org, containerDO, pdmUserDTO);
                    TyplmAuditLogUtil.info(pdmUserDTO.getOid(), pdmUserDTO.getOtype(), LogEventEnum.IMPORT);
                    successList.add(excelDTO);
                } catch (Exception var16) {
                    Exception e = var16;
                    log.error("创建用户失败失败！失败原因：" + e);
                    excelDTO.setMessage(ObjectUtils.isNotEmpty(e.getMessage()) ? e.getMessage() : e.toString());
                    errorList.add(excelDTO);
                    AuditLogDO auditLogDO = new AuditLogDO();
                    auditLogDO.setObjoid(BigInteger.ZERO);
                    auditLogDO.setObjotype("ty.inteplm.org.CTyUser");
                    auditLogDO.setOrgcontaineroid(orgOid);
                    auditLogDO.setOrgcontainerotype("ty.inteplm.org.CTyOrg");
                    auditLogDO.setContaineroid(pdmUserDTO.getContaineroid());
                    auditLogDO.setContainerotype(pdmUserDTO.getContainerotype());
                    auditLogDO.setTargetname(pdmUserDTO.getUsername());
                    TyplmAuditLogUtil.errorInfo(LogEventEnum.IMPORT, auditLogDO, e);
                }
            }

            result.put("successList", successList);
            result.put("errorList", errorList);
            TyplmLoggerUtil.debug(log, () -> {
                return "importUserInOrg的出参result为<==【{}】";
            }, () -> {
                return new Object[]{JSON.toJSONString(result)};
            });
            return result;
        }
    }

    public void downloadExcelTemplete(HttpServletResponse response) {
        String directory = "templates/";
        String fileName = "userImportTemplete.xlsx";
        DownLoadFileUtils.downLoadFile(response, directory, fileName);
    }

    public List<PdmUserDTO> queryPdmUserList() {
        Map<String, Object> param = new HashMap();
        return this.getUserListByParams(param);
    }

    public void checkPasswordStrength(String password) {
        List<EnumerationValueDTO> weakPasswordEnum = this.typlmEnumerationService.getItemValueListByEnumDefKey("WeakPassword");
        if (!CollUtil.isEmpty(weakPasswordEnum)) {
            List<String> weakPasswords = (List)weakPasswordEnum.stream().map((m) -> {
                return SecureUtil.sha256(m.getName());
            }).collect(Collectors.toList());
            if (weakPasswords.contains(password)) {
                throw UserErrorCodeEnum.PASSWORD_COMPLEXITY_IS_TOO_LOW.getException(new Object[0]);
            }
        }
    }

    public Boolean forceToChangePwd(String userName) {
        Map<String, Object> param = new HashMap();
        param.put("account", userName);
        List<PdmUser> pdmUserList = this.getUserListByParams(param, true);
        if (CollUtil.isEmpty(pdmUserList)) {
            return false;
        } else {
            String encryptPassword = ((PdmUser)pdmUserList.get(0)).getPassword();
            return encryptPassword == null;
        }
    }

    public String refreshToken(String token, HttpServletRequest request) throws IOException {
        if (StringUtils.isEmpty(token)) {
            throw UserErrorCodeEnum.TOKEN_DOES_NOT_EXIST.getException(new Object[0]);
        } else {
            String newToken = "";

            try {
                newToken = this.redisTokenUtil.refreshHeadToken(token);
            } catch (Exception var5) {
                Exception exception = var5;
                log.error("JWT校验失败：" + exception.getMessage());
            }

            return newToken;
        }
    }

    private void batchCheckSecurityLabel(List<PdmUserDTO> list) {
        if (!ObjectUtils.isEmpty(list)) {
            Set<String> securityLabelsSet = (Set)list.stream().filter((item) -> {
                return StringUtils.isNotBlank(item.getSecuritylabels());
            }).map(PdmUserDTO::getSecuritylabels).collect(Collectors.toSet());
            if (!ObjectUtils.isEmpty(securityLabelsSet)) {
                Map<String, Map<String, String>> enabledEnumItemsMap = this.typlmEnumerationService.getEnabledEnumItemsMap(Lists.newArrayList(new String[]{"SecurityLabels"}));
                Map<String, String> securityLabelsMap = (Map)ObjectUtils.defaultIfNull(enabledEnumItemsMap.get("SecurityLabels"), Maps.newHashMap());
                Collection<String> securityLabelsList = securityLabelsMap.values();
                Collection<String> unExistsSecurityLabels = org.apache.commons.collections4.CollectionUtils.subtract(securityLabelsSet, securityLabelsList);
                if (ObjectUtils.isNotEmpty(unExistsSecurityLabels)) {
                    throw new MessageException(UserErrorCodeEnum.USER_SECURITYLABELS_NOT_CONTAIN_ERROR, new Object[]{StringUtils.join(unExistsSecurityLabels, ","), StringUtils.join(securityLabelsList, ",")});
                }
            }
        }
    }

    private PdmUserExcelDTO coverUserToExcelDTO(PdmUserDTO pdmUserDTO, String msg) {
        PdmUserExcelDTO pdmUserExcelDTO = new PdmUserExcelDTO();
        BeanUtil.copyProperties(pdmUserDTO, pdmUserExcelDTO, new String[0]);
        pdmUserExcelDTO.setMessage(msg);
        return pdmUserExcelDTO;
    }

    public PdmUser createuserByDO(PdmUser pdmUser) {
        this.insert(pdmUser);
        return pdmUser;
    }

    public void deleteuser(BigInteger userId) {
        ((PdmUserMapper)this.mapper).batchDeleteByOid(Collections.singletonList(userId));
    }

    public void deletuserbylist(List<BigInteger> userIdlist) {
        ((PdmUserMapper)this.mapper).batchDeleteByOid(userIdlist);
    }

    public PdmUser updateuser(PdmUser pdmUser) {
        this.update(pdmUser);
        this.typlmAsyncHandleCache.asyncbatchDeleteUserCache(Collections.singletonList(pdmUser.getName()));
        return pdmUser;
    }

    public List<PdmUser> getUserListByParam(Map<String, Object> param) {
        return this.getUserListByParams(param, true);
    }

    private List<String> buildToRemoveList(List<Object> objectList) {
        List<String> toRemoveList = new ArrayList();
        if (CollUtil.isEmpty(objectList)) {
            return toRemoveList;
        } else {
            objectList.stream().map(String::valueOf).forEach((item) -> {
                if (item.contains(",")) {
                    toRemoveList.addAll((Collection)Arrays.stream(item.split(",")).collect(Collectors.toList()));
                } else {
                    toRemoveList.add(item);
                }

            });
            return toRemoveList;
        }
    }

    public int getOnlineUserDistinct() {
        int onlineUser = 0;
        List<String> redisKeys = this.typlmRedisService.getRedisKeys("adapter:user:token:*");
        List<String> kickoutKeys = this.typlmRedisService.getRedisKeys("flag:kickout:key:username:*");
        List<Object> kickoutValues = this.typlmRedisService.multiGet(kickoutKeys);
        List compeloutKeys;
        if (CollUtil.isNotEmpty(kickoutValues)) {
            compeloutKeys = this.buildToRemoveList(kickoutValues);
            redisKeys.removeAll(compeloutKeys);
        }

        compeloutKeys = this.typlmRedisService.getRedisKeys("flag:compelout:key:username:*");
        List<Object> compeloutValues = this.typlmRedisService.multiGet(compeloutKeys);
        if (CollUtil.isNotEmpty(compeloutValues)) {
            List<String> toRemoveList = this.buildToRemoveList(compeloutValues);
            redisKeys.removeAll(toRemoveList);
        }

        Set<String> onlineUserDistinct = new HashSet();
        if (CollUtil.isNotEmpty(redisKeys)) {
            Iterator var8 = redisKeys.iterator();

            while(var8.hasNext()) {
                String redisKey = (String)var8.next();
                int redisKeyLen = redisKey.length();
                int length = "adapter:user:token:".length();
                String noTokenCacheKey = redisKey.substring(length, redisKeyLen);
                int index = noTokenCacheKey.indexOf(":");
                String name = noTokenCacheKey.substring(0, index);
                if (StringUtils.isNotEmpty(name)) {
                    onlineUserDistinct.add(name);
                }
            }

            onlineUser = onlineUserDistinct.size();
        }

        return onlineUser;
    }

    public List<PdmUser> fuzzyQuery(Map<String, Object> params) {
        Example example = new Example(this.getEntityClass(), true, true);
        Example.Criteria criteria = example.createCriteria();
        if (CollUtil.isNotEmpty(params)) {
            String status;
            if (params.containsKey("name")) {
                status = params.get("name").toString();
                criteria.andCondition("upper(name) like ", "%" + status.toUpperCase(Locale.ROOT) + "%");
            }

            if (params.containsKey("fullname")) {
                status = params.get("fullname").toString();
                criteria.andCondition("upper(fullname) like ", "%" + status.toUpperCase(Locale.ROOT) + "%");
            }

            if (params.containsKey("status")) {
                status = params.get("status").toString();
                criteria.andCondition(" status = ", Integer.parseInt(status));
            }
        }

        example.setOrderByClause("createstamp desc");
        return this.simpleQueryListByExample(example);
    }

    public List<PdmUser> getUserListByParams(Map<String, Object> params, boolean upperName) {
        Map<String, Object> params1 = new HashMap();
        String name = null;
        if (CollUtil.isNotEmpty(params)) {
            Set<Map.Entry<String, Object>> entrySet = params.entrySet();
            String keyItem;
            String value;
            if (CollUtil.isNotEmpty(entrySet)) {
                for(Iterator<Map.Entry<String, Object>> it = entrySet.iterator(); it.hasNext(); name = this.screenUser(params1, name, keyItem, value)) {
                    Map.Entry<String, Object> entry = (Map.Entry)it.next();
                    keyItem = (String)entry.getKey();
                    value = entry.getValue().toString();
                }
            }
        }

        Example example = new Example(this.getEntityClass(), true, true);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(name)) {
            if (upperName) {
                criteria.andCondition("upper(name)=", name.toUpperCase(Locale.ROOT));
                if ("app".equals(params.get("source"))) {
                    criteria.orCondition("upper(email)=", name.toUpperCase(Locale.ROOT));
                    criteria.orCondition("upper(telephone)=", name.toUpperCase(Locale.ROOT));
                }
            } else {
                params1.put("name", name);
            }
        }

        criteria.andEqualTo(params1);
        example.setOrderByClause("createstamp desc");
        return this.simpleQueryListByExample(example);
    }

    private String screenUser(Map<String, Object> params1, String name, String keyItem, String value) {
        switch (keyItem) {
            case "securitylabels":
                params1.put("securitylabels", value);
                break;
            case "account":
                name = value;
                break;
            case "status":
                if ("1".equals(value)) {
                    params1.put("disabled", 0);
                }

                if ("0".equals(value)) {
                    params1.put("disabled", 1);
                }
                break;
            case "username":
                params1.put("fullname", value);
                break;
            case "sex":
                params1.put("ext1", value);
                break;
            case "tele":
                params1.put("telephone", value);
                break;
            case "oid":
                params1.put("oid", new BigInteger(value));
        }

        return name;
    }

    public void deletuserByListWithCache(List<BigInteger> userIdlist) {
        List<PdmUser> pdmUserList = this.selectByOids(userIdlist);
        this.deletuserbylist(userIdlist);
        List<String> refreshCacheList = (List)pdmUserList.stream().map(CTyEntityBaseDO::getName).collect(Collectors.toList());
        this.typlmAsyncHandleCache.asyncbatchDeleteUserCache(refreshCacheList);
        List<PrincipalEntity> principalEntityList = Convert.toList(PrincipalEntity.class, pdmUserList);
        this.typlmAsyncHandleCache.asyncBatchDeletePrincipalLinkCache(principalEntityList);
    }

    public List<PdmUser> getUserListByOids(Collection<BigInteger> oids) {
        return this.selectByOids(oids);
    }

    public List<PdmUserDTO> getUserListbyParamsFuzzy(Map<String, Object> params) {
        List<PdmUserDTO> pdmUserDTOList = new ArrayList();
        Example example = new Example(PdmUser.class, true, true);
        Example.Criteria orCriteria = example.createCriteria();
        Example.Criteria andCriteria = example.createCriteria();
        if (CollUtil.isNotEmpty(params)) {
            Iterator var6 = params.entrySet().iterator();

            while(var6.hasNext()) {
                Map.Entry<String, Object> key = (Map.Entry)var6.next();
                String value = key.getValue().toString();
                String keyItem = (String)key.getKey();
                if (StringUtils.isNotEmpty(value)) {
                    this.switchKeyItem(keyItem, value, orCriteria, andCriteria);
                }
            }
        }

        example.and(andCriteria);
        example.setOrderByClause("createstamp desc");
        List<PdmUser> pdmUserList = this.simpleQueryListByExample(example);
        List<BigInteger> idList = (List)pdmUserList.stream().map(CTyEntityBaseDO::getOid).collect(Collectors.toList());
        this.getAgentInfo(pdmUserList, idList, pdmUserDTOList);
        TyplmLoggerUtil.debug(log, () -> {
            return "getUserListbyParamsFuzzy的出参pdmUserDTOList为<==【{}】";
        }, () -> {
            return new Object[]{pdmUserDTOList.size()};
        });
        return pdmUserDTOList;
    }
}
